package models
import (
//"errors"
	_"log"
	_"github.com/astaxie/beego/validation"
	//."smart_home/lib"
	"github.com/astaxie/beego/orm"
	"fmt"
	"strconv"
	"github.com/astaxie/beego"
	"time"
)
const layout = "2006-01-02 15:04:05"

type FileManager struct {
	Id          		int		`orm:"unique;auto;pk"`
	UserID				int64
	FilePath			string
	FileName			string
	FileData			string		`orm:"type(text)"`
	UploadDate			string//time.Time	`orm:"type(datetime);auto_now_add" `
	Size				string
}
var data_url string = beego.AppConfig.String("data_url")
func init() {
	// 需要在init中注册定义的model
	orm.RegisterModel(new(FileManager))
}
func AddFilePath(user_id string,file_name string,bit_flow string) (string,error) {
	UserID ,_:= strconv.ParseInt(user_id,10,64)
//	var  size_f float64
//	size_f = float64(len(bit_flow))/float64(1024)
//	size := strconv.FormatFloat(size_f,'b',2,64)+"kb"
	//fmt.Println("bit_flow len",len(bit_flow))
	byte_len := len(bit_flow)
	var byte_str string
	if byte_len > 1000{
		byte_str = strconv.FormatInt(int64(byte_len/1000),10)+"."+strconv.FormatInt(int64(byte_len%1000),10)+"KB"
	}else{
		byte_str = strconv.FormatInt(int64(byte_len%1000),10)+"B"
	}
	file := FileManager{UserID:UserID,FilePath:data_url+file_name,FileName:file_name,FileData:bit_flow,Size:byte_str,UploadDate:time.Now().Format(layout)}
	o := orm.NewOrm()
	mFileManager,count,err :=  GetFilePathCount(file.UserID)
	if err != nil{
		return file.FilePath, err

	}
	fmt.Println("count",count)
	if  count >= 2{
		fmt.Println("count > 2")
		mFileManager[0].FileData = file.FileData
		mFileManager[0].FileName = file.FileName
		mFileManager[0].FilePath = file.FilePath
		mFileManager[0].Size = file.Size
		//mFileManager[0].UploadDate = file.UploadDate
		mFileManager[0].UploadDate = time.Now().Format(layout)
		//mFileManager[0].UserID = file.Size
		err = UpdateFilePath(&mFileManager[0])
		fmt.Println("err",err)
	}else{
		_, err = o.Insert(&file)
		if err != nil{
			fmt.Println("err",err)
		}
	}

	return file.FilePath, err
}
func GetFilePathCount(UserID int64) ([]FileManager ,int64,error) {
	o := orm.NewOrm()
	//file = FileManager{UserID: UserID}
	var mFileManager []FileManager
	file := new(FileManager)
	qs := o.QueryTable(file)
	//	var offset int64
	//	if page <= 1 {
	//		offset = 0
	//	} else {
	//		offset = (page - 1) * page_size
	//	}.Limit(page_size, offset)
	count,err := qs.Filter("UserID",UserID).OrderBy("UploadDate").All(&mFileManager)
	return mFileManager,count,err
}


func UpdateFilePath(file *FileManager)(error){
	o := orm.NewOrm()
	//if o.Read(file) == nil {
		if num, err := o.Update(file); err == nil {
			fmt.Println(num)
			return nil
		}else {
			fmt.Println("Update err", err)
			return err
		}
	//}
	//return nil
}
func GetFileList(UserID int64)([]FileManager, int64){
	o := orm.NewOrm()
	file_manage := new(FileManager)
	var files []FileManager
	qs := o.QueryTable(file_manage)
	qs = qs.Filter("UserID",UserID)
	count,err := qs.All(&files)
	fmt.Println("count",count)
	fmt.Println("err",err)

	fmt.Println("files",files)
	if count > 0 {
		for i := int64(0); i < count; i++ {
			fmt.Println("i", i)
			files[i].FileData = "";
		}
	}
	//      fmt.Println("count",count)
	//      fmt.Println("files",files)
	return files, count
}
//通过用户id获取用户
//@param id  int64  用户的ID
//@return   User      返回用户的数据结构体
//@return   error     返回错误，如果无错，返回值为空
func GetFileById(id int) (file FileManager ,err error) {
	file = FileManager{Id: id}
	o := orm.NewOrm()
	err = o.Read(&file, "Id")
	if err == orm.ErrNoRows {
		//		fmt.Println("查询不到")
		return file,err
	} else if err == orm.ErrMissPK {
		//		fmt.Println("找不到主键")
		return file,err
	}
	//	fmt.Println("找到数据：",user)
	return file,err
}
